import requests
import json
import logging
import threading
import sys
from socket import *

# config读取
config = json.loads(open(r'sendConfig.json', encoding='utf-8').read())

# 监控ID
monitor = config["monitor"]
if monitor == -1:
    sys.exit(0)
# 心跳
heart = config["heart"]
# 转发
forward = config["forward"]
# 推送
serverPush = config["serverPush"]

# 设置请求头
headers = {'Content-Type': 'application/json; charset=UTF-8'}

# 开设Socket端口
PORT = config["port"]
BUFSIZ = 20480
ADDR = ('', PORT)


# 创建一个logger
logger = logging.getLogger('listen')
logger.setLevel(logging.DEBUG)

# 创建一个handler，用于写入日志文件
fh = logging.FileHandler('see.log')
fh.setLevel(logging.DEBUG)

# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

# 给logger添加handler
logger.addHandler(fh)


# 监听连接去处理请求
def domain():
    threading.Thread(target=selfHeart, ).start()
    toForward(str(monitor), '**心跳&信息转发 启动**', False, False, '脚本启动', '脚本启动')
    tcpSerSock = socket(AF_INET, SOCK_STREAM)
    tcpSerSock.bind(ADDR)
    # 设置最大连接数
    tcpSerSock.listen(10)
    while True:
        try:
            print('waiting for connection...' + str(PORT))
            Sock, addr = tcpSerSock.accept()
            threading.Thread(target=processing, args=(Sock, addr,)).start()
        except:
            print("continue")


# 处理接收到消息之后的处理
def processing(tcpCliSock, addr):
    print('connection success , wait MSG······', addr)
    data = tcpCliSock.recv(BUFSIZ)
    print("收到了发送的请求")
    msg = data.decode("utf-8").replace('\'', '"')
    tcpCliSock.close()
    inner = json.loads(msg)
    type = inner['type']
    if type == 'heart':
        toHeart(str(inner['monitor']))
    elif type == 'forward':
        toForward(str(inner['monitor']), str(inner['msg']), inner['isText'], inner['isSpeak'], str(inner['text']), str(inner['speak']))
    elif type == 'serverPush':
        toServerPush(str(inner['server']), inner['data'])


# 心跳转发
def toHeart(monitorId):
    try:
        requests.get(url=(heart + monitorId), timeout=3, headers=headers)
    except:
        try:
            requests.get(url=(heart + monitorId), timeout=3, headers=headers)
        except:
            print('两次心跳都失败')


# 转发推送
def toForward(monitorId, msg, isText, isSpeak, text, speak):
    noEnter = msg.replace('\n', '')
    data = {
        "msgtype": "markdown",
        "markdown": {
            "title": "通知:" + (noEnter[15] if len(noEnter) > 15 else noEnter),
            "text": msg
        },
        "at": {
            "isAtAll": True  # 是否@所有人
        },
        "isText": isText,
        "isSpeak": isSpeak,
        "text": text,
        "speak": speak
    }
    try:
        print("开始转发")
        print(forward + monitorId)
        requests.post(url=(forward + monitorId), headers=headers, data=json.dumps(data), timeout=5)
    except error as e:
        print(e)
        print("无法请求到转发接口，转发失败，继续监控")
        logger.error(str(e) + '--------toForward')


# 转发推送
def toServerPush(server, data):
    try:
        requests.post(url=(serverPush + server), headers=headers, data=json.dumps(data), timeout=5)
    except error as e:
        print(e)
        print("无法请求到推送接口，推送失败，继续监控")
        logger.error(str(e) + '--------toServerPush')


# 自己的心跳
def selfHeart():
    toHeart(str(monitor))
    threading.Timer(60, selfHeart, ()).start()


domain()
